package com.htgd.gardenexpo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.htgd.gardenexpo.dao.*;
import com.htgd.gardenexpo.dto.GeConGoalSportsDTO;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.service.IGeConGoalSportsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.htgd.gardenexpo.vo.MyTaskDetails;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

import static com.htgd.gardenexpo.utils.CalculationUtils.getSpeed;
import static com.htgd.gardenexpo.utils.CommonUtils.*;
import static com.htgd.gardenexpo.utils.CommonUtils.compareAndReturnLarger;
import static com.htgd.gardenexpo.utils.RSAUtil.decryptionString;
import static com.htgd.gardenexpo.utils.SportsUtils.calculateCalories;
import static com.htgd.gardenexpo.utils.TimeUtils.formatSecondsToTime;

/**
 * <p>
 * 目标跑 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-04-02
 */
@Service
public class GeConGoalSportsServiceImpl extends ServiceImpl<GeConGoalSportsMapper, GeConGoalSports> implements IGeConGoalSportsService {

    @Autowired
    private GeConGoalSportsMapper geConGoalSportsMapper;

    @Autowired
    private GeConSportsMaxMapper geConSportsMaxMapper;

    @Autowired
    private GeConGoalSportsTaskMapper geConGoalSportsTaskMapper;

    @Autowired
    private WxUserDao wxUserDao;

    @Override
    public CommonResult add(GeConGoalSportsDTO geConGoalSportsDTO, String openId) {
        //解密距离检验
        String distanceEncryption = geConGoalSportsDTO.getSign();
        String flagEncryption = geConGoalSportsDTO.getFlag();
        try {
            String decryptionString = decryptionString(distanceEncryption);
            String timeStamp = decryptionString(flagEncryption);
            //对比距离
            if(decryptionString.equals(geConGoalSportsDTO.getDistance())){

                boolean exists = lambdaQuery().eq(GeConGoalSports::getTimeStamp, timeStamp)
                        .eq(GeConGoalSports::getTaskId,geConGoalSportsDTO.getTaskId())
                        .exists();
                if(exists){
                    return CommonResult.error("该数据已存在，请勿重复添加");
                }else {
                    // 给定时间戳和间隔时间
                    long timestamp = Long.parseLong(timeStamp);  // 时间戳（毫秒）
                    // 将间隔时间转换为毫秒并减去
                    long startTimestamp = timestamp - (geConGoalSportsDTO.getTime() * 1000);
                    // 转换为日期格式
                    // 将时间戳转换为Instant
                    Instant instant = Instant.ofEpochMilli(startTimestamp);
                    Instant instant2 = Instant.ofEpochMilli(timestamp);
                    // 转换为LocalDateTime，假设是UTC时区（或者使用默认时区）
                    ZoneId chinaZoneId = ZoneId.of("Asia/Shanghai");
                    LocalDateTime startDateTime = instant.atZone(chinaZoneId).toLocalDateTime();
                    LocalDateTime endDateTime = instant2.atZone(chinaZoneId).toLocalDateTime();

                    //计算卡路里
                    WxUser byOpenId = wxUserDao.getByOpenId(openId);
                    double calorie = 0d;
                    if(byOpenId.getWeight()!=null){
                        calorie = calculateCalories(Double.parseDouble(geConGoalSportsDTO.getDistance()),byOpenId.getWeight());
                    }else {
                        calorie = calculateCalories(Double.parseDouble(geConGoalSportsDTO.getDistance()),70);
                    }

                    GeConGoalSports geConGoalSports = new GeConGoalSports();
                    BeanUtils.copyProperties(geConGoalSportsDTO,geConGoalSports);
                    geConGoalSports.setTimeStamp(timeStamp);
                    geConGoalSports.setBeginTime(startDateTime);
                    geConGoalSports.setEndTime(endDateTime);
                    geConGoalSports.setCalorie(String.valueOf(calorie));
                    geConGoalSportsMapper.insert(geConGoalSports);

                    GeConSportsMax geConSportsMax = geConSportsMaxMapper.selectOne(new LambdaQueryWrapper<GeConSportsMax>().eq(GeConSportsMax::getOpenId, openId));
                    if(geConSportsMax!=null){
                        String maxMileage = compareAndReturnLarger(geConSportsMax.getMaxMileage(),geConGoalSportsDTO.getDistance());
                        String maxDuration = compareAndReturnLarger(geConSportsMax.getMaxDuration(), String.valueOf(geConGoalSportsDTO.getTime()));
                        String maxCalorie = compareAndReturnLarger(geConSportsMax.getMaxCalorie(), String.valueOf(calorie));
                        geConSportsMaxMapper.update(
                                new GeConSportsMax(),  // 实体类实例（通常为空）
                                new LambdaUpdateWrapper<GeConSportsMax>()
                                        .eq(GeConSportsMax::getOpenId, openId)  // 设置更新条件：openId 匹配
                                        .set(GeConSportsMax::getMaxMileage, maxMileage)  // 设置需要更新的字段值
                                        .set(GeConSportsMax::getMaxDuration, maxDuration)  // 更新最大时长
                                        .set(GeConSportsMax::getMaxCalorie, maxCalorie)  // 更新最大卡路里
                        );
                    }
                }
            }else {
                return CommonResult.error("数据检验失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return CommonResult.success("添加成功");
    }

    @Override
    public CommonResult getTaskDetails(String taskId) {
        //基础数据
        MyTaskDetails myTaskDetails = geConGoalSportsMapper.getTaskDetails(taskId);
        //运动时间
        String sportsTime = formatTimeRange(myTaskDetails.getBeginTime(), myTaskDetails.getEndTime());
        myTaskDetails.setSportsTime(sportsTime);
        //时长
        String duration = formatSecondsToTime(Long.parseLong(myTaskDetails.getDuration()));
        myTaskDetails.setDuration2(duration);
        //配速
        String speed = getSpeed(Long.parseLong(myTaskDetails.getDuration()), Double.parseDouble(myTaskDetails.getMileage()));
        myTaskDetails.setSpeed(speed);
        //轨迹
        List<String> tracks = geConGoalSportsMapper.getTaskTrack(taskId);
        String s = mergeList(tracks);
        myTaskDetails.setTrack(s);
        //用户信息
        GeConGoalSportsTask geConGoalSportsTask = geConGoalSportsTaskMapper.selectById(taskId);
        WxUser wxUser = wxUserDao.getByOpenId(geConGoalSportsTask.getOpenId());
        myTaskDetails.setUserName(wxUser.getName());
        myTaskDetails.setUrl(wxUser.getUrl());
        return CommonResult.success("查询成功",myTaskDetails);
    }
}
